<?php
namespace App\Think\SdkGame;

date_default_timezone_set('PRC');

class Datang{

    protected $agentid;
    protected $descode;
    protected $md5code;
    protected $api_url;

    // 官方网站地址：http://datqp.com
    // 免费试玩地址：http://play.datqp.com
    // API接入地址： http://ng.datqp.com
    // 管理后台地址：http://manager.datqp.com dtadminbt 000000

    public function __construct()
    {
        // 商户唯一编码  
        $this->agentid = '10028';
        // 参数加密编码  
        $this->descode = '4401AB72A2BBBA04';
        // 请求校验加密编码    
        $this->md5code = 'BAA5BD5F65B9C224';
        // api地址
        $this->api_url = 'https://ng.datqp.com/';

        $this->plat_type = 'Datang';
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            'account'     => $param['account'],
            'nickname'    => $param['account'],
            'headindex'   => rand(0,11),
            'linecode'    => '',
            "lastloginip" => request()->ip(),
            'gamebackurl' => '',
            'logintype'   => 1,
            'gameid'      => 0
        );
        $url = $this->build_request(0, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        $res = $this->register($param);
        return ['code'=>$res['code'], 'url'=>$res['url'] ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            "account" => $param['account']
        );
        $url = $this->build_request(7, $req_data);
        $res = $this->sendRequest($url);
        return ['code'=>$res['code'], 'balance'=>(float)$res['totalScore'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $req_data = array(
            "account" => $param['account'],
            "orderid" => $param['orderid'],
            "score"   => $param['money']
        );
        $url = $this->build_request(2, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $req_data = array(
            "account" => $param['account'],
            "orderid" => $param['orderid'],
            "score"   => $param['money']
        );
        
        $url = $this->build_request(3, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    public function transOutInfo($param){
        $req_data = array(
            "account" => $param['account']
        );
        $url = $this->build_request(3, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }

    /**
     * 查询玩家的上下分订单信息
     */
    public function orderStatus($param){
        $req_data = array(
            "account" => $param['account'],
            "orderid" => $param['orderid'],
        );
        $url = $this->build_request(4, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }

    /**
     * 玩家信息查询
     */
    public function userInfo($param){
        $req_data = array(
            "account" => $param['account']
        );
        $url = $this->build_request(7, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 玩家状态信息查询
     */
    public function userStatus($param){
        $req_data = array(
            "account" => $param['account']
        );
        $url = $this->build_request(5, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    
    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        $req_data = array(
            "startTime" => ((strtotime($param['startTime']))+8*3600)*1000,
            "endTime"   => ((strtotime($param['endTime']))+8*3600)*1000
        );
        $url = $this->build_request(6, $req_data, 'GetRecordHandle');
        $res = $this->sendRequest($url);
        //数据返回处理
        $list = @$res['list'];
        $rs = $raw_data = [];
        $status = 1;
        if(is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                //流水
                if($v['Profit'] < 0)  $money_valid = -$v['Profit'];
                if($v['Profit'] >= 0) $money_valid = $v['Profit']<$v['AllBet'] ? $v['Profit'] : $v['AllBet'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $v['GameID'],
                    'game_name'     => @$this->room_name($v['RoomID']),
                    'game_user'     => $v['Account'],
                    'bet_id'        => $v['ObjectID'],
                    'money_bet'     => $v['AllBet'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $v['Profit'],
                    'money_fee'     => $v['Revenue'],
                    'createtime'    => strtotime($v['GameStartTime']),
                    'updatetime'    => strtotime($v['GameEndTime']),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $v['ObjectID'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($v['GameEndTime']);
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == -101 ? 1 : $res['code'];
        return $res;
    }

    /**
     * 比赛注单拉取
     */
    public function matchLogSync($param){
        $req_data = array(
            "startTime" => $param['startTime'],
            "endTime"   => $param['endTime']
        );
        $url = $this->build_request(11, $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }



    /**
     * 业务
     */
    //游戏列表
    public function game_list(){
        $list = [
            '0'=>'大厅',
            '1'=>'捕鱼合集',
            '720'=>'百人二八杠',
            '830'=>'抢庄牛牛',
            '210'=>'红黑大战',
            '220'=>'炸金花',
            '860'=>'三公',
            '900'=>'百人龙虎',
            '600'=>'21 点',
            '930'=>'百人牛牛',
            '730'=>'抢庄牌九',
            '630'=>'十三水',
            '870'=>'通比牛牛',
            '---'=>'德州扑克',
            '400'=>'港式五张（至尊五张）',
            '1810'=>'水果机',
            '500'=>'金蝉捕鱼',
            '890'=>'看牌抢庄牛牛',
            '1350'=>'幸运转盘',
            '240'=>'抢庄炸金花',
            '1960'=>'奔驰宝马',
            '820'=>'抢庄选三张（三公）',
            '300'=>'抢庄选三张（炸金花）',
            '1940'=>'金鲨银鲨',
            '880'=>'百变抢庄牛牛',
            '200'=>'红黑斗牛',
            '1820'=>'新水果机',
            '510'=>'李逵劈鱼',
            '520'=>'人鱼传说',
            '530'=>'大闹天宫',
            '610'=>'斗地主',
            '1830'=>'水浒传',
        ];
        return $list;
    }
    public function game_name($gameid){
        $list = $this->game_list();
        return isset($list[$gameid]) ? $list[$gameid] : '未知游戏';
    }

    //房间列表
    private function room_list(){
        $list = [
            '7201'=>'百人二八杠',
            '8301'=>'抢庄牛牛体验房',
            '8302'=>'抢庄牛牛初级房',
            '8303'=>'抢庄牛牛中级房',
            '8304'=>'抢庄牛牛高级房',
            '8321'=>'银牛大赛',
            '8322'=>'金牛大赛',
            '8323'=>'小牛大赛',
            '8324'=>'牛王大赛',
            '2101'=>'红黑大战',
            '2201'=>'炸金花体验房',
            '2202'=>'炸金花初级房',
            '2203'=>'炸金花中级房',
            '2204'=>'炸金花高级房',
            '8601'=>'三公体验房',
            '8602'=>'三公初级房',
            '8603'=>'三公中级房',
            '8604'=>'三公高级房',
            '9001'=>'龙虎斗',
            '6001'=>'21 点体验房',
            '6002'=>'21 点初级房',
            '6003'=>'21 点中级房',
            '6004'=>'21 点高级房',
            '9301'=>'百人牛牛',
            '7301'=>'抢庄牌九体验房',
            '7302'=>'抢庄牌九初级房',
            '7303'=>'抢庄牌九中级房',
            '7304'=>'抢庄牌九高级房',
            '6301'=>'十三水体验房（常规场）',
            '6302'=>'十三水初级房（常规场）',
            '6303'=>'十三水中级房（常规场）',
            '6304'=>'十三水高级房（常规场）',
            '6305'=>'十三水体验房（极速场）',
            '6306'=>'十三水初级房（极速场）',
            '6307'=>'十三水中级房（极速场）',
            '6308'=>'十三水高级房（极速场）',
            '8701'=>'通比牛牛体验房',
            '8702'=>'通比牛牛初级房',
            '8703'=>'通比牛牛中级房',
            '8704'=>'通比牛牛高级房',
            '4001'=>'至尊五张体验房（港式五张）',
            '4002'=>'至尊五张初级房（港式五张）',
            '4003'=>'至尊五张中级房（港式五张）',
            '4004'=>'至尊五张高级房（港式五张）',
            '18101'=>'水果机',
            '5001'=>'金蟾捕鱼体验房',
            '5002'=>'金蟾捕鱼初级房',
            '5003'=>'金蟾捕鱼中级房',
            '5004'=>'金蟾捕鱼高级房',
            '8901'=>'看牌抢庄牛牛体验房',
            '8902'=>'看牌抢庄牛牛初级房',
            '8903'=>'看牌抢庄牛牛中级房',
            '8904'=>'看牌抢庄牛牛高级房',
            '13501'=>'幸运转盘',
            '2401'=>'抢庄扎金花体验房',
            '2402'=>'抢庄扎金花初级房',
            '2403'=>'抢庄扎金花中级房',
            '2404'=>'抢庄扎金花高级房',
            '8201'=>'抢庄选三张（三公）体验房',
            '8202'=>'抢庄选三张（三公）初级房',
            '8203'=>'抢庄选三张（三公）中级房',
            '8204'=>'抢庄选三张（三公）高级房',
            '3001'=>'抢庄选三张（扎金花）体验房',
            '3002'=>'抢庄选三张（扎金花）初级房',
            '3003'=>'抢庄选三张（扎金花）中级房',
            '3004'=>'抢庄选三张（扎金花）高级房',
            '19601'=>'奔驰宝马',
            '19401'=>'金鲨银鲨',
            '8811'=>'黄金厅体验房',
            '8812'=>'黄金厅初级房',
            '8813'=>'黄金厅中级房',
            '8814'=>'黄金厅高级房',
            '8815'=>'黄金厅大师房',
            '8816'=>'黄金厅至尊房',
            '8821'=>'金玉厅体验房',
            '8822'=>'金玉厅初级房',
            '8823'=>'金玉厅中级房',
            '8824'=>'金玉厅高级房',
            '8825'=>'金玉厅大师房',
            '8826'=>'金玉厅至尊房',
            '8831'=>'皇家厅体验房',
            '8832'=>'皇家厅初级房',
            '8833'=>'皇家厅中级房',
            '8834'=>'皇家厅高级房',
            '8835'=>'皇家厅大师房',
            '8836'=>'皇家厅至尊房',
            '8841'=>'豪华厅体验房',
            '8842'=>'豪华厅初级房',
            '8843'=>'豪华厅中级房',
            '8844'=>'豪华厅高级房',
            '8845'=>'豪华厅大师房',
            '8846'=>'豪华厅至尊房',
            '8851'=>'传奇厅体验房',
            '8852'=>'传奇厅初级房',
            '8853'=>'传奇厅中级房',
            '8854'=>'传奇厅高级房',
            '8855'=>'传奇厅大师房',
            '8856'=>'传奇厅至尊房',
            '8861'=>'风骚厅体验房',
            '8862'=>'风骚厅初级房',
            '8863'=>'风骚厅中级房',
            '8864'=>'风骚厅高级房',
            '8865'=>'风骚厅大师房',
            '8866'=>'风骚厅至尊房',
            '8871'=>'荣耀厅体验房',
            '8872'=>'荣耀厅初级房',
            '8873'=>'荣耀厅中级房',
            '8874'=>'荣耀厅高级房',
            '8875'=>'荣耀厅大师房',
            '8876'=>'荣耀厅至尊房',
            '2001'=>'红黑斗牛',
            '18201'=>'新水果机',
            '5102'=>'李逵劈鱼初级房',
            '5103'=>'李逵劈鱼中级房',
            '5104'=>'李逵劈鱼高级房',
            '5202'=>'人鱼传说初级房',
            '5203'=>'人鱼传说中级房',
            '5204'=>'人鱼传说高级房',
            '5302'=>'大闹天宫初级房',
            '5303'=>'大闹天宫中级房',
            '5304'=>'大闹天宫高级房',
            '6101'=>'斗地主体验场',
            '6102'=>'斗地主初级场',
            '6103'=>'斗地主中级场',
            '6104'=>'斗地主高级场',
            '18301'=>'水浒传'
        ];
        return $list;
    }
    private function room_name($roomid){
        $list = $this->room_list();
        return isset($list[$roomid]) ? $list[$roomid] : '未知房间';
    }

    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url,$post_data=array(), $req_type=0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //POST
        if($req_type == 1){ 
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        // print_r($contents);die;
        // echo $url;
        // print_r($post_data);
        // print_r($con);

        $contents = json_decode($contents, true);
        //业务处理
        $res = $contents['data'];
        if(!isset($res['code'])) $res['code'] = -1;
        if($res['code'] > 0) $res['code'] = -$res['code'];
        if($res['code'] == 0) $res['code'] = 1;
        return $res;
    }
    
    private function build_request($type=0, array $param, $act='GameHandle'){
        $timestamp = time()*1000;
        $param = http_build_query($param);
        $paraValue = urlencode(DatangAes::encrypt($param, $this->descode));
        $key = md5($this->agentid.$timestamp.$this->md5code);
        return $this->api_url.$act.'?agentid='.$this->agentid."&timestamp={$timestamp}&type={$type}&paraValue={$paraValue}&key={$key}";
    }
}


/*加密类*/
class DatangAes{
    public static function encrypt($input, $key) {
        return self::mcryptEncrypt($input,$key);
        // if (substr(PHP_VERSION, 0, 1) == '7') {
        //     return self::opensslEncrypt($input,$key);
        // }else{
        //     return self::mcryptEncrypt($input,$key);
        // }
    }
    public static function decrypt($input, $key) {
        return self::mcryptDecrypt($input,$key);
        // if (substr(PHP_VERSION, 0, 1) == '7') {
        //     return self::opensslDecrypt($input,$key);
        // }else{
        //     return self::mcryptDecrypt($input,$key);
        // }
    }
    /**
     * [encrypt description]
     * 使用mcrypt库进行加密
     * @param  [type] $input
     * @param  [type] $key
     * @return [type]
     */
    public static function mcryptEncrypt($input, $key) {
        @$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = self::pkcs5Pad($input, 16);
        @$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        @$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);//MCRYPT_DEV_URANDOM
        @mcrypt_generic_init($td, $key, $iv);
        @$data = mcrypt_generic($td, $input);
        @mcrypt_generic_deinit($td);
        @mcrypt_module_close($td);
        $data = base64_encode($data);
        return $data;
    }
    /**
     * [pkcs5Pad description]
     * @param  [type] $text
     * @param  [type] $blocksize
     * @return [type]
     */
    private static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    /**
     * [decrypt description]
     * 使用mcrypt库进行解密
     * @param  [type] $sStr
     * @param  [type] $sKey
     * @return [type]
     */
    public static function mcryptDecrypt($sStr, $sKey) {
        @$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);//MCRYPT_DEV_URANDOM
        @$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, base64_decode($sStr), MCRYPT_MODE_ECB, $iv);
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
    /**
     * [opensslDecrypt description]
     * 使用openssl库进行加密
     * @param  [type] $sStr
     * @param  [type] $sKey
     * @return [type]
     */
    public static function opensslEncrypt($sStr, $sKey, $method = 'AES-256-ECB'){
        $str = openssl_encrypt($sStr,$method,$sKey);
        return $str;
    }
    /**
     * [opensslDecrypt description]
     * 使用openssl库进行解密
     * @param  [type] $sStr
     * @param  [type] $sKey
     * @return [type]
     */
    public static function opensslDecrypt($sStr, $sKey, $method = 'AES-256-ECB'){
        $str = openssl_decrypt($sStr,$method,$sKey);
        return $str;
    }
}
